package com.dev.module_zqc_sleep.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.dev.module_ui_composable.theme.JetComposableTheme
import com.dev.module_zqc_sleep.mvi.ui.SettingAlarmScreen
import com.dev.module_zqc_sleep.mvi.vm.AlarmViewModel
import com.fwlst.lib_base.utils.GlideEngine
import com.fwlst.lib_base.utils.JtXXPermissions

import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener

class SettingAlarmActivity : AppCompatActivity() {

    private val alarmViewModel by viewModels<AlarmViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            JetComposableTheme {
                SettingAlarmScreen(
                    alarmViewModel = alarmViewModel,
                    onBackPress = { time ->
                        finishActivity(time)
                    },
                    onSelectAudio = { selectAudio() }
                )
            }
        }
    }

    private fun selectAudio() {
        JtXXPermissions.requestGallery(this){
            PictureSelector.create(this)
                .openGallery(SelectMimeType.ofAudio())
                .isDisplayCamera(false)
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(1)
                .setMinSelectNum(1)
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>) {
                        alarmViewModel.updateAudioPath(result[0].fileName, result[0].path)
                    }

                    override fun onCancel() {
                    }
                })
        }
    }

    private fun finishActivity(time: String) {
        val returnIntent = Intent()
        returnIntent.putExtra("resultKey", time)
        setResult(Activity.RESULT_OK, returnIntent)
        finish()
    }

}